const router = require("@koa/router")()
const openidModel = require("../../model/api/User")
const couponModel = require("../../model/api/Coupon")
const { localTime } = require("../../utils/index");
const { getCode2Session } = require("../../request/tt");
const { ttappid, ttsecret, appid, secret } = require("../../config/index");
const { getKey } = require("../../request/wx");
const stepModel = require("../../model/api/Step")
// console.log(getKey)
const assert = require("http-assert");
const session = require("koa-session");
const user = require("../../model/api/User");
const { ReplSet } = require("mongodb");
router.get("/", async (ctx) => {
  ctx.body = "欢迎来到user模块"
})


/* 获取openID */
router.post("/wxOpenId", async (ctx) => {

  try {
    const code = ctx.request.body.code;
    assert(code, 422, "缺少code")
    const res = await getKey(appid, secret, code);
    const key = JSON.parse(res.body);
    if (res.errcode) {
      return ctx.body = {
        status: -1,
        message: res.errmsg
      }
    }
    ctx.body = {
      status: 0,
      message: "成功",
      data: JSON.parse(res.body)
    }
  } catch (error) {
    console.log(error)
  }
})


/* 注册 */
router.post("/login_applet", async (ctx) => {

  const params = ctx.request.body;
  const user = await openidModel.findOne(params);

  if (!user) {
    const res = await openidModel.create({ ...params, time: localTime() })
    const coupon = await couponModel.find({ user: res._id });
    if (res.__v === 0) {
      ctx.body = {
        status: 1,
        message: "创建成功",
        data: { ...res._doc, coupon: coupon.length || 0 }
      }
    } else {
      ctx.body = {
        status: 0,
        message: "创建失败",
        data: null
      }
    }
  } else {
    ctx.body = {
      status: 1,
      message: "用户已存在",
      data: user
    }
  }

})


/* 查询用户 */
router.post("/inquire", async (ctx) => {

  const params = ctx.request.body;

  try {
    const user = await openidModel.findOne(params);
    if (user && user.__v === 0) {
      ctx.body = {
        status: 0,
        message: 'success',
        data: user
      }
    } else {
      ctx.body = {
        status: 1,
        message: "未查询到",
        data: null
      }
    }
  } catch (error) {
    console.log(error)
    ctx.body = {
      status: 0,
      message: error.code,
      data: null
    }
  }

})


/* 获取key */
router.get("/getKey", async (ctx) => {
  try {
    const code = ctx.query.code;
    assert(code, 422, "缺少code")
    const res = await getKey(appid, secret, code);
    const key = JSON.parse(res.body);
    let data;
    key.errcode ? data = key :
      data = await openidModel.create({ openId: key.openid, session_key: key.session_key, time: localTime() });

    ctx.body = {
      status: 0,
      message: "success",
      data
    }
  } catch (error) {
    ctx.body = {
      status: -1,
      message: error.message,
      data: null
    }
    console.log(error)
  }
})


/* 存入步数*/
router.post("/deposit_step", async (ctx) => {

  try {
    const WXBizDataCrypt = require("../../utils/WXBizDataCrypt")
    const { encryptedData, iv, code, openId, id } = ctx.request.body;
    let step;
    assert(code, 422, "缺少code")
    assert(openId, 422, "缺少openId");
    console.log("======>", openId)
    const key_res = await getKey(appid, secret, code);
    const key = JSON.parse(key_res.body);
    const decode = new WXBizDataCrypt(appid, key.session_key);
    step = decode.decryptData(encryptedData, iv);
    const res = await stepModel.findOne({ openId });
    let total = 0;
    step.stepInfoList.map((item, index) => {
      total += item.step
    });
    if (res && res.__v === 0) {
      stepModel.findOneAndUpdate({ openId }, { $set: { today: step.stepInfoList[30].step || 0, time: localTime(), total, } }, (err) => {})
    } else {
      stepModel.create({ today: step.stepInfoList[30].step || 0, time: localTime(), total, openId })
    }
    // }
    ctx.body = {
      status: 0,
      message: "success",
      data: step
    }
  } catch (error) {
    console.log(error)
    ctx.body = {
      status: -1,
      message: "fail",
      data: error.message
    }
  }
})


/* 获取步数 */

router.post("/step", async (ctx) => {
  try {
    const WXBizDataCrypt = require("../../utils/WXBizDataCrypt")
    const { encryptedData, iv, code, openId } = ctx.request.body;
    assert(code, 422, "缺少code")
    const res = await getKey(appid, secret, code);
    const key = JSON.parse(res.body);
    if (key.errcode) {
      return ctx.body = {
        status: 0,
        message: "success",
        data: key
      }
    } else {
      const decode = new WXBizDataCrypt(appid, key.session_key);
      const step = decode.decryptData(encryptedData, iv);
      ctx.body = {
        status: 0,
        message: "success",
        data: step
      }
    }
  } catch (error) {
    console.log(error)
    ctx.body = {
      status: -1,
      message: "fail",
      data: error.message
    }
  }
})

/* 注册 */
router.post("/register", async (ctx) => {
  try {
    const data = ctx.request.body;
    assert(data, 422, "缺少参数");
    const res = await openidModel.create({ ...data, time: localTime() })
    ctx.body = {
      status: 0,
      message: "success",
      data: res
    }
  } catch (error) {
    ctx.body = {
      status: -1,
      message: "fail",
      data: error.message
    }
  }


})

// const limit = Number(ctx.query.limit) || 30;
// const skip = Number(limit * ctx.query.page) || 0;
// const res = await stepModel.find({}, null, { sort: { total: 1 }, skip, limit })
//查询运动步数排名
router.get("/ranking", async (ctx) => {
  const openId = ctx.query.openId;
  const res = await stepModel.aggregate([
    { $sort: { today: -1 } }, //按照分数排序
    { $group: { _id: null, all: { $push: "$openId" } } }, // 将所有排序结果push到all数组中，方便下面使用$indexOfArray
    { $project: { _id: 0, total: { $size: "$all" }, index: { $indexOfArray: ["$all", openId] } } } // 这里的openid为要查找名次的openid
  ])
  ctx.body = {
    status: 0,
    data: res,
    message: "success"
  }
})

/* 获取运动总排行 */
router.get("/step_ranking", async (ctx) => {
  try {
    const limit = Number(ctx.query.limit) || 30;
    const skip = Number(ctx.query.page) * limit || 0;
    const res = await stepModel.aggregate([{
      $lookup: { from: "users", localField: 'openId', foreignField: 'openId', as: "userInfo" }
    }, {
      $lookup: { from: "likes", localField: 'openId', foreignField: "loved", as: "loves" }
    }, {
      $project: { _id: 0, today: 1, userInfo: 1, loves: 1 }
    }, {
      $sort: { today: -1 }
    }, {
      $match: {
        userInfo: {
          $size: 1
        }
      }
    }]).skip(skip).limit(limit)
    ctx.body = {
      status: 0,
      data: res,
      message: "success"
    }
  } catch (error) {
    console.log(error)
    ctx.bod = {
      status: -1,
      message: error.message,
      data: null
    }
  }
})

// 更改用户背景
router.post("/changeBackground", async (ctx) => {
  try {
    const { src, id } = ctx.request.body;
    assert(id, 402, "请带上id");
    const res = await openidModel.findByIdAndUpdate(id, { $set: { background: src } })
    if (res.__v === 0) {
      ctx.body = {
        status: 0,
        message: "success",
        data: res
      }
    } else {
      ctx.body = {
        status: 0,
        message: "fail",
        data: res
      }
    }
  } catch (error) {
    console.log(error)
    ctx.bod = {
      status: -1,
      message: "fail",
      data: error.message
    }
  }

})

module.exports = router